﻿using System;
using System.Collections.Generic;
using System.Text;

namespace OpenGameEngine.Logging
{
    public static class LogProvider
    {
        private static List<ILogProvider> logProviders { get; set; }
        private static object netLock;

        static LogProvider()
        {
            netLock = new object();
            logProviders = new List<ILogProvider>();
        }

        public static void RegisterProvider(ILogProvider logProvider)
        {
            logProviders.Add(logProvider);
        }

        public static Boolean UnregisterProvider(ILogProvider logProvider)
        {
            return logProviders.Remove(logProvider);
        }

        public static void Log(string log)
        {
            Log(log, LogImportance.Low);
        }

        public static void Log(Exception e)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append(e.Message);
            builder.AppendLine();
            InternalExceptionLogger(builder, e);

            string _log = builder.ToString();

            Log(_log, LogImportance.High);
        }

        private static void InternalExceptionLogger(StringBuilder builder, Exception e)
        {
            builder.AppendLine(e.StackTrace);
            Exception inner = e.InnerException;

            if (inner != null)
                InternalExceptionLogger(builder, inner);
        }

        public static void Log(string log, LogImportance importance)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append(DateTime.Now.ToString("[hh:mm:ss.fff] "));
            builder.Append(log);

            string _log = builder.ToString();

            lock (netLock)
                foreach (ILogProvider provider in logProviders)
                    provider.Log(_log, importance);
        }
    }
}
